package com.cn.longdistancebusstation.personal.privilege;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.cn.longdistancebusstation.R;
import com.cn.longdistancebusstation.annotation.PrivilegeStatus;
import com.cn.longdistancebusstation.base.BaseActivity;
import com.cn.longdistancebusstation.global.GlobalVariable;
import com.cn.longdistancebusstation.httpHelper.HttpHelper;
import com.cn.longdistancebusstation.httpapi.HttpService;
import com.cn.longdistancebusstation.model.ListResultII;
import com.cn.longdistancebusstation.model.Privilege;

import java.math.BigDecimal;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;

public class UseablePrivilegeListActivity extends BaseActivity {

    private List<Privilege> mPrivilegeList;
    private RecyclerView mRecyclerView;
    private CustomAdapter mAdapter;
    private String mSinglePrivilegeID;
    private List<String> mPrivilegeIDList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_useable_privilege_list);
        //
        getTitleTextView().setText("优惠券");
        showMenu1("确认", 0);
        //
        initData();
        //
        getPrivileges();
    }

    private void initData(){
        //
        Intent intent = getIntent();
        mSinglePrivilegeID = intent.getStringExtra("id");
        mPrivilegeIDList = (ArrayList)intent.getSerializableExtra("ids");
        //
        mPrivilegeList = new ArrayList<>();
        mRecyclerView = (RecyclerView)findViewById(R.id.useablePrivilegeList_recyclerView);
        mRecyclerView.setBackgroundColor(getResources().getColor(R.color.privilegeBgColor));
        mAdapter = new CustomAdapter();
        mRecyclerView.setAdapter(mAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
    }
    //
    private void getPrivileges(){
        showHud();
        Retrofit retrofit = new HttpHelper.HttpServiceBuilder().build().getRetrofit();
        HttpService httpService = retrofit.create(HttpService.class);
        Call<ListResultII<Privilege>> call = httpService.getPrivileges(GlobalVariable.getUserID());
        call.enqueue(new Callback<ListResultII<Privilege>>() {
            @Override
            public void onResponse(Call<ListResultII<Privilege>> call, Response<ListResultII<Privilege>> response) {
                hideHud();
                ListResultII<Privilege> result = response.body();
                if(result.getHead().getSuccess()){
                    List<Privilege> list = result.getData();
                    for(Privilege privilege : list){
                        if(isPrivilegeValid(privilege)){
                            if(mPrivilegeIDList.contains(privilege.getId())){}
                            else
                            {
                                if(mSinglePrivilegeID.equals(privilege.getId())){
                                    privilege.setChoose(true);
                                }
                                mPrivilegeList.add(privilege);
                            }
                        }
                    }
                    mAdapter.notifyDataSetChanged();
                }
                else{
                    Toast.makeText(UseablePrivilegeListActivity.this, result.getHead().getMsg(), Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<ListResultII<Privilege>> call, Throwable t) {
                hideHud();
                Toast.makeText(UseablePrivilegeListActivity.this, t.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
    }
    //判断优惠券是否可用
    private Boolean isPrivilegeValid(Privilege privilege){
        Date startDate = null;
        Date endDate;
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar = Calendar.getInstance();
        //
        try
        {
            startDate = dateFormat.parse(privilege.getStartDate());
        }
        catch(ParseException e)
        {}
        calendar.setTime(startDate);
        calendar.add(Calendar.DAY_OF_MONTH, privilege.getValidDays());
        endDate = calendar.getTime();
        //
        //
        calendar = Calendar.getInstance();
        Date todayDate = calendar.getTime();
        if(privilege.getStatus() == 0){
            //未使用(未过期、已过期)
            if(endDate.getTime() < todayDate.getTime()){
                //已过期
                return false;
                //
            }
            else{
                //未过期
                return true;
            }
        }
        else{
            //已使用
            return false;
        }
    }

    @Override
    public void onMenu1Click() {
        super.onMenu1Click();
        Privilege privilege = new Privilege();
        for(Privilege tempPrivilege : mPrivilegeList){
            if(tempPrivilege.getChoose()){
                privilege = tempPrivilege;
                break;
            }
        }
        Intent intent = getIntent();
        intent.putExtra("data", privilege);
        setResult(RESULT_OK, intent);
        finish();
    }

    //
    private class CustomViewHolder extends RecyclerView.ViewHolder{
        private ImageView mLogoImgView;
        private ImageView mStatusImgView;
        private ImageView mBgImgView;
        private ImageView mRadioImgView;
        private TextView mDiscountTV;
        private TextView mDescTV;
        private TextView mTimeTV;
        private Privilege mPrivilege;

        public CustomViewHolder(View itemView) {
            super(itemView);
            mLogoImgView = (ImageView) itemView.findViewById(R.id.privilege_recycler_item_logo_imageView);
            mStatusImgView = (ImageView)itemView.findViewById(R.id.privilege_recycler_item_status_imageView);
            mBgImgView = (ImageView)itemView.findViewById(R.id.privilege_recycler_item_bg_imageView);
            mRadioImgView = (ImageView)itemView.findViewById(R.id.privilege_recycler_item_radio_imageView);
            mDiscountTV = (TextView)itemView.findViewById(R.id.privilege_recycler_item_discount_textView);
            mDescTV = (TextView)itemView.findViewById(R.id.privilege_recycler_item_desc_textView);
            mTimeTV = (TextView)itemView.findViewById(R.id.privilege_recycler_item_time_textView);
            //
            mRadioImgView.setVisibility(View.VISIBLE);
            mRadioImgView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    for(Privilege privilege : mPrivilegeList){
                        if(privilege.getId().equals(mPrivilege.getId())){}
                        else{
                            privilege.setChoose(false);
                        }
                    }
                    if(mPrivilege.getChoose()){
                        mPrivilege.setChoose(false);
                        mRadioImgView.setImageResource(R.mipmap.insurance_normal);
                    }
                    else{
                        mPrivilege.setChoose(true);
                        mRadioImgView.setImageResource(R.mipmap.insurance_select);
                    }
                    mAdapter.notifyDataSetChanged();
                }
            });
        }

        public void bindData(Privilege privilege) {
            //
            mPrivilege = privilege;
            privilege.setPrivilegeStatus(PrivilegeStatus.PRIVILEGE_STATUS_UNUSE);
            mBgImgView.setImageResource(R.mipmap.ticket_unuse_background);
            mLogoImgView.setImageResource(R.mipmap.ticket_unuse_logo);
            mStatusImgView.setVisibility(View.INVISIBLE);
            //
            BigDecimal decimal = new BigDecimal(privilege.getDiscount());
            decimal = decimal.multiply(new BigDecimal("10")).setScale(1, BigDecimal.ROUND_DOWN);
            mDiscountTV.setText(decimal.toString() + " 折");
            //
            mDescTV.setText("使用范围：");
            //
            Date startDate = null;
            Date endDate;
            DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
            Calendar calendar = Calendar.getInstance();
            //
            try
            {
                startDate = dateFormat.parse(privilege.getStartDate());
            }
            catch(ParseException e)
            {}
            calendar.setTime(startDate);
            calendar.add(Calendar.DAY_OF_MONTH, privilege.getValidDays());
            endDate = calendar.getTime();
            String strEndDate = dateFormat.format(endDate);
            //
            mTimeTV.setText("使用时间：" + privilege.getStartDate() + "--" + strEndDate);
            //判断单选框是否选中
            if(privilege.getChoose()){
                mRadioImgView.setImageResource(R.mipmap.insurance_select);
            }
            else{
                mRadioImgView.setImageResource(R.mipmap.insurance_normal);
            }
        }
    }
    //
    private class CustomAdapter extends RecyclerView.Adapter<CustomViewHolder>{
        @Override
        public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
            LayoutInflater layoutInflater = LayoutInflater.from(UseablePrivilegeListActivity.this);
            View view = layoutInflater.inflate(R.layout.privilege_recycler_item, parent, false);
            return new CustomViewHolder(view);
        }

        @Override
        public void onBindViewHolder(CustomViewHolder holder, int position) {
            Privilege privilege = mPrivilegeList.get(position);
            holder.bindData(privilege);
        }

        @Override
        public int getItemCount() {
            return mPrivilegeList.size();
        }
    }
}
